package com.css.fxfzfxqh.modules.reportmanagement.reportutil;

import com.alibaba.fastjson.JSON;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.style.BorderStyle;
import com.deepoove.poi.data.style.Style;
import com.deepoove.poi.policy.DynamicTableRenderPolicy;
import com.deepoove.poi.policy.TableRenderPolicy;
import com.deepoove.poi.util.TableTools;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/***
 *2 建筑物地震易损性 表格策略
 */
public class JzwysxCustomTableMethodPolicy extends DynamicTableRenderPolicy{

    // 填充数据所在行数
    int listsStartRow = 1;

    @Override
    public void render(XWPFTable table, Object data)  throws   Exception{
        if (null == data) {
            return;
        }
        List<Map<String,Object>> mapList = ( List<Map<String,Object>>)data;
        table.removeRow(listsStartRow);
        if (!CollectionUtils.isEmpty(mapList))
        {
            List<RowRenderData> dataList = new ArrayList<>();
            for (int x=0;x<mapList.size();x++)
            {
                Map<String,Object> obj=(Map) mapList.get(x);
                //  省
                // 	市
                // 	县
                // 	结构类型
                // 	设防情况
                //  破坏程度
                //  烈度    VI（%）
                //  VII（%）
                //  VIII（%）
                //  IX（%）
                //  X（%）
                RowRenderData renderData = Rows.of(
                        obj.get("province")+"",
                        obj.get("city")+"",
                        obj.get("county")+"",
                        obj.get("structure_type")+"",
                        obj.get("fortify")+"",
                        obj.get("damage")+"",
                        obj.get("rate_6")+"",
                        obj.get("rate_7")+"",
                        obj.get("rate_8")+"",
                        obj.get("rate_9")+"",
                        obj.get("rate_10")+""

                ).create();
                dataList.add(renderData);
            }
            Style style = new Style("宋体",10.5);
            //table循环插入行,dataList从后到前插入
            for (int i = dataList.size() - 1; i >= 0; i--)
            {
                XWPFTableRow insertNewTableRow = table.insertNewTableRow(listsStartRow);
                for (int j = 0; j < 11; j++)//11列数据
                {
                    insertNewTableRow.createCell();
                }
                // 渲染单行数据
                TableRenderPolicy.Helper.renderRow(table.getRow(listsStartRow),dataList.get(i) ,style);
            }
            // 边框和样式
            TableTools.borderTable(table, BorderStyle.DEFAULT);
            //获取array的分组统计信息
            Map<String, List<Map<String,Object>>> groupMap1 = mapList.stream().collect(groupingBy(p->p.get("province").toString()));
            int colIndex=0;
            mergeCell(table,data,dataList,groupMap1,colIndex);

            Map<String, List<Map<String,Object>>> groupMap2 = mapList.stream().collect(groupingBy(p->p.get("city").toString()));
            colIndex=1;
            mergeCell(table,data,dataList,groupMap2,colIndex);

            Map<String, List<Map<String,Object>>> groupMap3 = mapList.stream().collect(groupingBy(p->p.get("county").toString()));
            colIndex=2;
            mergeCell(table,data,dataList,groupMap3,colIndex);

            Map<String, List<Map<String,Object>>> groupMap4 = mapList.stream().collect(groupingBy(p->p.get("structure_type").toString()));
            colIndex=3;
            mergeCell(table,data,dataList,groupMap4,colIndex);

            //Map<String, List<Map<String,Object>>> groupMap5 = list.stream().collect(groupingBy(p->p.get("fortify").toString()));
            // 多个属性分组，按照门派和性别分组
            Map<String, List<Map<String,Object>>> groupMap5 = mapList.stream().collect(Collectors.groupingBy(x -> x.get("county") + "&" + x.get("structure_type") + "&" + x.get("fortify")));

            colIndex=4;
            mergeCell(table,data,dataList,groupMap5,colIndex);

        }
    }


    private void mergeCell(XWPFTable table,Object data,List<RowRenderData> dataList,Map<String,List<Map<String,Object>>> groupMap,Integer colIndex) throws  Exception{
        //获取array的分组统计信息
       // List<Map<String,Object>> list =(List<Map<String,Object>>) data;
       // Map<String, List<Map<String,Object>>> groupMap = list.stream().collect(groupingBy(p->p.get("province").toString()));
        List<String> groupList = JSON.parseArray(JSON.toJSONString(groupMap.keySet()), String.class);
        //table的第1列数据合并省的区域合并
        int columnCount = table.getRow(listsStartRow).getTableCells().size();
        for(int i=0;i<dataList.size();i++){
            String famliy = "";
            for (int y = 0; y < columnCount; y++)//11列数据
            {
                if(y<6){
                    famliy = "宋体";
                }else{
                    famliy = "Times New Roman";
                }
                //XWPFTableCell cell = table.getRow(i + 1).getCell(y);
                XWPFTableCell cell = table.getRow(i + listsStartRow).getCell(y);
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
                for (XWPFParagraph paragraph : cell.getParagraphs()) {
                    paragraph.setAlignment(ParagraphAlignment.CENTER);
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (XWPFRun run : runs) {
                        run.setFontSize(10.5);
                        run.setFontFamily(famliy);
                    }
                }
            }
        }
        for (int i = 0; i < dataList.size(); i++)
        {
            //处理第一列机组合并
            //Object province = dataList.get(i).getCells().get(0).getParagraphs().get(0).getContents().get(0).toString();
            Object province = null;
            if(colIndex!=4){
                province = dataList.get(i).getCells().get(colIndex).getParagraphs().get(0).getContents().get(0).toString();
            }else{
                province = (
                        dataList.get(i).getCells().get(colIndex-2).getParagraphs().get(0).getContents().get(0).toString() + "&" +
                        dataList.get(i).getCells().get(colIndex-1).getParagraphs().get(0).getContents().get(0).toString() + "&" +
                        dataList.get(i).getCells().get(colIndex).getParagraphs().get(0).getContents().get(0).toString());
            }
            String province_name = String.valueOf(province);
            List<Map<String, Object>> maps = groupMap.get(province_name);
            if(PlatformObjectUtils.isNotEmpty(maps) && maps.size()>0){
                if((i + 1)<=dataList.size()&&(i + maps.size())<=dataList.size())
                {
                    // 合并第0列的第i+2行到第i+unitSize行的单元格
                    //TableTools.mergeCellsVertically(table, 0, i + 1, i + provinceNameNum.size());

                    TableTools.mergeCellsVertically(table, colIndex, i + 1, i + maps.size());
//                    //处理垂直居中
//                    for (int y = 0; y < 11; y++)//11列数据
//                    {
//                        XWPFTableCell cell = table.getRow(i + 1).getCell(y);
//                        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
//                    }
                    i=i+maps.size()-1;
                }
            }

//            for (int j = 0; j < groupList.size(); j++)
//            {
//                String provinceName = groupList.get(j);
//                List<Map<String,Object>> provinceNameNum= groupMap.get(provinceName);
//                if (province_name.equals(provinceName))
//                {
//                    if((i + 1)<=dataList.size()&&(i + provinceNameNum.size())<=dataList.size())
//                    {
//                        // 合并第0列的第i+2行到第i+unitSize行的单元格
//                        //TableTools.mergeCellsVertically(table, 0, i + 1, i + provinceNameNum.size());
//
//                        TableTools.mergeCellsVertically(table, colIndex, i + 1, i + provinceNameNum.size());
//                        //处理垂直居中
//                        for (int y = 0; y < 11; y++)//11列数据
//                        {
//                            XWPFTableCell cell = table.getRow(i + 1).getCell(y);
//                            cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
//                        }
//                        i=i+provinceNameNum.size()-1;
//                    }
//                }
//            }
        }

    }

}